package org.diffshop.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.diffshop.common.utils.PageUtils;
import org.diffshop.common.utils.Query;
import org.diffshop.product.dao.CategoryBrandRelationDao;
import org.diffshop.product.dao.CategoryDao;
import org.diffshop.product.entity.CategoryEntity;
import org.diffshop.product.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    private CategoryBrandRelationDao categoryBrandRelationDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询商品分类树状结构的业务方法
     *
     * @return 树状结构的分类列表
     */
    @Override
    public List<CategoryEntity> queryCateGoryListWithTree() {
        // 1 查询所有的商品分类
        List<CategoryEntity> all = baseMapper.selectList(null);

        // 2 建立分类的树状结构
        List<CategoryEntity> categoryTree = all.stream().filter(category -> {
            return category.getParentCid().equals(0L);
        }).sorted((pre, next) -> {
            return (pre == null ? 0 : pre.getSort()) - (next == null ? 0 : next.getSort());
        }).map(oneLevelNode -> {
            oneLevelNode.setChildren(queryCategoryChildrenByPid(oneLevelNode.getCatId(), all));
            return oneLevelNode;
        }).collect(Collectors.toList());

        return categoryTree;
    }

    /**
     * 批量删除分类
     *
     * @param idList
     */
    @Override
    public void removeCategoryByIds(List<Long> idList) {
        //TODO 判断是否有其他模块引用了当前分类

        baseMapper.deleteBatchIds(idList);
    }

    /**
     * 获取分类路径
     *
     * @param catId
     * @return
     */
    @Override
    public Long[] getCategoryPath(Long catId) {
        List<Long> ids = new ArrayList<>();
        ids.add(catId);
        LambdaQueryWrapper<CategoryEntity> wrapper = new LambdaQueryWrapper();
        wrapper.eq(CategoryEntity::getCatId, catId);
        CategoryEntity category = baseMapper.selectOne(wrapper);
        while (category.getParentCid() != 0){
            wrapper.clear();
            wrapper.eq(CategoryEntity::getCatId, category.getParentCid());
            category = baseMapper.selectOne(wrapper);
            ids.add(category.getCatId());
        }
        // 反转集合中的元素
        Collections.reverse(ids);
        return ids.toArray(new Long[ids.size()]);
    }

    /**
     * 更新商品
     * @param category
     */
    @Transactional
    @Override
    public void updateDetail(CategoryEntity category) {
        this.updateById(category);

        // 更新关联分类表的信息
        categoryBrandRelationDao.updateCategory(category.getCatId(), category.getName());

        // TODO: 2024/6/13 更新其他关联表
    }

    /**
     * 根据pid，查询商品分类列表
     *
     * @param catId
     * @param all
     * @return
     */
    private static List<CategoryEntity> queryCategoryChildrenByPid(Long catId, List<CategoryEntity> all) {
        List<CategoryEntity> result = all.stream().filter(category -> {
            return category.getParentCid().equals(catId);
        }).map(parentNode -> {
            parentNode.setChildren(queryCategoryChildrenByPid(parentNode.getCatId(), all));
            return parentNode;
        }).sorted(
                Comparator.comparingInt(pre -> (pre.getSort() == null ? 0 : pre.getSort()))
        ).collect(Collectors.toList());

        return result;
    }


}
